package com.leet.competition;

import java.util.*;

public class MinStone {
    public int minStoneSum(int[] piles, int k) {
      int[] map = new int[100001];
      int ans = 0;
        for(Integer pile:piles){
           map[pile]++;
       }
        for(int i = map.length-1;i >= 1 ; i--){
            if(k <= 0) break;
            while(map[i] != 0){
                if(i%2==0){
                    map[i/2]++;
                }else{
                    map[(i+1)/2]++;
                }
                map[i]--;
                k--;
            }
        }
        for(int i = 0 ; i < map.length;i++){
            if(map[i]!=0){
                ans += map[i]*i;
            }
        }
        return ans;
    }
}
